/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 2 -*- */
/**
* @file daemon.cpp
* 
* Library for easy control of the daemonize process.
*
* @author Miguel Ángel Vílchez López 2008 <sacra@openmatica.es> 
*
* Codigo is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* Codigo is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License along
* with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "daemon.hpp"
#include "debug.cpp"

CMDaemon::CMDaemon(const char* filepid="/var/run/mokardu",int priority=0,bool debug=false,const char* filedebug=""):debug(debug,filedebug)
{
	pid_t pid,sid;

	this->debug.debug("Trying to create a new process...");
	pid=fork();
	if(pid<0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		exit(EXIT_FAILURE);
	}
        this->pid=pid;
	//Exit from process father(original)
	if(pid>0)
	{	exit(EXIT_SUCCESS);	}

	this->debug.debug("Trying to create a new session...");
	if((sid=setsid())<0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		exit(EXIT_FAILURE);
	}

	this->debug.debug("Trying to close stdin, stdout and stderror");
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
	
	this->debug.debug("Trying to stablish the priority of the new process...");
	if(setpriority(sid,sid,priority)<0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
	}

        
	//Write to pid file

}

CMDaemon::~CMDaemon()
{
}

int CMDaemon::getPid()
{
    return this->pid;
}
